# configs/auth.py
import requests

from configs.config import settings  # 导入 settings
from core.logger import Logger


class AuthManager:
    """认证管理器，自动获取 & 刷新 Token"""
    token = None

    @classmethod
    def get_auth_headers(cls):
        """获取认证头部信息"""
        method = settings["auth"]["method"]  # 直接从 settings 中获取配置

        Logger.logger().info("Client-Id 配置内容: {}".format(settings["auth"]["Client-Id"]))  # 打印配置内容

        Logger.logger().info("method 的值为：{}".format(method))

        if method == "jwt":
            return cls._get_jwt_headers()

        elif method == "api_key":
            return {"X-API-KEY": settings["auth"]["api_key"]}
        elif method == "basic":
            from requests.auth import HTTPBasicAuth
            auth = HTTPBasicAuth(settings["auth"]["username"], settings["auth"]["password"])
            Logger.logger().info("auth 为：{}".format(auth))
            return {"Authorization": auth}
        else:
            return {}

    @classmethod
    def _get_jwt_headers(cls):
        """获取 JWT Token 并返回包含该 Token 的认证头"""
        if cls.token is None:
            # 拼接完整的登录接口 URL
            login_url = settings["base_url"] + settings["auth"]["token_url"]

            Logger.logger().info("login_url为：{}".format(login_url))

            # 发起请求获取 JWT Token
            response = requests.post(
                login_url,  # 使用拼接后的 URL
                data={"username": settings["auth"]["username"],
                      "password": settings["auth"]["password"]
                      },
                headers={
                      "Client-Id": settings["auth"]["Client-Id"],
                      "Content-Type": settings["auth"]["Content-Type"]}
            )
            Logger.logger().info("response为：{}".format(response))
            Logger.logger().info("status_code为：{}".format(response.status_code))
            Logger.logger().info("response.text为：{}".format(response.text))

            if response.status_code == 200:
                cls.token = response.json()["data"]["token"]
                Logger.logger().info("获取 Token 成功，token 为：{}".format(cls.token))

        return {"Authorization": f"Bearer {cls.token}"}


if __name__ == '__main__':
    AuthManager.get_auth_headers()
